using B.S.XZYData.Api.Read.Application.Command.Approval;
using B.S.XZYData.Domain.ZSH;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using Microsoft.Extensions.Logging;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.XZYData.Api.Read.Application.Handler.Approval
{
    /// <summary>
    /// 查询我的申请记录处理器
    /// </summary>
    public class QueryMyApplicationsHandler : IRequestHandler<QueryMyApplicationsCommand, ApiResult<MyApplicationPageResult>>
    {
        private readonly IBaseRepository<WorkflowInstanceModel> _workflowInstanceRepo;
        private readonly ILogger<QueryMyApplicationsHandler> _logger;

        public QueryMyApplicationsHandler(
            IBaseRepository<WorkflowInstanceModel> workflowInstanceRepo,
            ILogger<QueryMyApplicationsHandler> logger)
        {
            _workflowInstanceRepo = workflowInstanceRepo;
            _logger = logger;
        }

        public async Task<ApiResult<MyApplicationPageResult>> Handle(QueryMyApplicationsCommand request, CancellationToken cancellationToken)
        {
            var res = new ApiResult<MyApplicationPageResult>();
            try
            {
                // 构建查询条件 - 只查询当前用户发起的申请
                var query = _workflowInstanceRepo.GetAll()
                    .Where(x => x.ApplicantUserName == request.ApplicantUserName);

                // 筛选条件
                if (!string.IsNullOrEmpty(request.WorkOrderCode))
                {
                    query = query.Where(x => x.WorkOrderCode.Contains(request.WorkOrderCode));
                }

                if (!string.IsNullOrEmpty(request.ProcessName))
                {
                    query = query.Where(x => x.ProcessName.Contains(request.ProcessName));
                }

                if (!string.IsNullOrEmpty(request.Status))
                {
                    query = query.Where(x => x.Status == request.Status);
                }

                if (request.CreateTimeStart.HasValue)
                {
                    query = query.Where(x => x.CreateTime >= request.CreateTimeStart.Value);
                }

                if (request.CreateTimeEnd.HasValue)
                {
                    query = query.Where(x => x.CreateTime <= request.CreateTimeEnd.Value.AddDays(1));
                }

                // 按创建时间倒序排列
                query = query.OrderBy(x => x.CreateTime, OrderByType.Desc);

                // 分页查询
                var totalCount = await query.CountAsync();
                var totalPages = (int)Math.Ceiling((double)totalCount / request.PageSize);

                var data = await query
                    .Skip((request.PageIndex - 1) * request.PageSize)
                    .Take(request.PageSize)
                    .ToListAsync();

                // 转换为DTO
                var dtoList = data.Select(x => new MyApplicationDto
                {
                    Id = x.Id,
                    WorkflowId = x.WorkflowId,
                    WorkOrderCode = x.WorkOrderCode,
                    WorkOrderNo = x.WorkOrderNo,
                    ProcessName = x.ProcessName,
                    ProcessCode = x.ProcessCode,
                    Title = x.Title,
                    StepName = x.StepName,
                    AuditUserName = x.AuditUserName,
                    Status = x.Status,
                    CreateTime = x.CreateTime,
                    CompletedTime = x.CompletedTime,
                    FormData = x.FormData,
                    CanResubmit = x.Status == "驳回" // 只有驳回状态才能重新提交
                }).ToList();

                res.Code = ApiEnum.Success;
                res.Msg = "查询成功";
                res.Data = new MyApplicationPageResult
                {
                    TotalCount = totalCount,
                    PageIndex = request.PageIndex,
                    PageSize = request.PageSize,
                    TotalPages = totalPages,
                    Data = dtoList
                };

                return res;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询我的申请记录失败");
                res.Code = ApiEnum.Fail;
                res.Msg = "查询失败：" + ex.Message;
                return res;
            }
        }
    }
} 